
from apitest.engine.const.enums import RType
from apitest.engine.const.model import Auth
from apitest.lib.fwe_lib.client import FWApiService
from apitest.lib.fwe_lib.model import FWLoginReq
from .ucaccount_lib.client import QaDataManagerService
from .ucaccount_lib.model import AddSessionReq, GetUserByMobileReq


class LoginApp:
    fwe = "wheel_engine"
    cloud = "cloud_passport"
    ca = "center_account"


class AccountClient:

    def __init__(self, token: str, app_id: str = None):
        self.token = token
        self.app_id = app_id
        self.auth = Auth()
        self.auth.oauth.update(dict(owner=self.token))
        self.client = QaDataManagerService(app=LoginApp.ca, auth=self.auth)

    def get_uid(self, mobile: str, app_id: str = None):
        if app_id is None:
            app_id = self.app_id
        resp = self.client.MGetUserByMobile(json=GetUserByMobileReq(mobile=[mobile], app_id=app_id))
        if resp.status_code != 0 or not resp.data:
            raise RuntimeError("获取手机号对应uid失败，手机号不属于而是账号服务手机号，错误信息：%s, data: %s" % (
                resp.message, resp.data))
        uid = resp.data.get(mobile)
        return uid

    def get_session(self, mobile: str, app_id: str = None, did: str = None):
        if app_id is None:
            app_id = self.app_id
        uid = self.get_uid(mobile, app_id)
        resp = self.client.GetAddSession(json=AddSessionReq(user_id=uid, app_id=app_id, did=did))
        if resp.status_code != 0 or not resp.data:
            raise RuntimeError("获取session失败，请重试，错误信息：%s, data: %s" % (resp.message, resp.data))
        session = resp.data.session_key
        return session


class FweClient:

    def __init__(self, session: str):
        self.auth = Auth()
        self.auth.cookie.update(dict(sessionid=session))
        self.client = FWApiService(app=LoginApp.fwe, auth=self.auth)

    def get_fwe_session(self, app_id: str, app_key: str):
        resp = self.client.FWLogin(json=FWLoginReq(app_key=app_id, aid=app_key), rtype=RType.raw)
        if not resp.json()["data"]:
            raise Exception("request error：获取session失败")
        fw_account_session_key = resp.cookies.get("fw_account_session_key")
        return fw_account_session_key
